<?php
/**
 * CRMLite Contact Model
 *
 * @final
 * @package        Crmlite_Model
 * @version        $Id: ContactModel.php 49 2007-09-06 07:17:07Z etng2004 $
 * @copyright      2006-2007 ETE.CN
 * @author         Yi BO  <etng2004@gmail.com>
 * @license        PHP Version 3.0 {@link http://www.php.net/license/3_0.txt}
 */


/**
 * 联系人表
 */
class Crmlite_Db_Table_Contact extends Crmlite_Db_Table {
    protected $_name = "contacts";
    protected $_primary = "id";
}

class ContactModel extends Crmlite_Model
{
    /**
     * 插入联系人数据库，如果为第一条记录则设置为主要联系人
     *
     * @param array $record 联系人数据
     */
    public function insert(&$record)
    {
        if(parent::insert($record))
        {
            if($this->count("client_id={$record['client_id']}")==1)
            {
                $this->setPrimary($record['client_id'], $record['id']);
            }
            return true;
        }
        return false;
    }
    /**
     * 设置某联系人为响应客户的主要联系人
     *
     * @param int $client_id    客户id
     * @param int $id           联系人id
     * @return bool
     */
    public function setPrimary($client_id, $id)
    {
        $sql = "UPDATE " . $this->dbt->getTable() . " SET is_primary=IF(id={$id}, 'Y', 'N') WHERE client_id={$client_id}";
        $this->db->query($sql);
        return $this->asyncPrimaryContact($client_id);
    }
    /**
	 * 获取主要联系人信息
	 *
	 * @param int $client_id   客户id
	 * @param string $field    需要获取的信息字段，如果要获取全部，请留空
	 * @return mixed
	 */
    public function getPrimaryContact($client_id, $field = null)
    {
        $where = array(
        "client_id = {$client_id}",
        "is_primary='Y'",
        );
        if($contacts = $this->findAll($where, null, 1))
        {
            $contact = array_shift($contacts);
            if(!is_null($field) && isset($contact[$field]))
            {
                return $contact[$field];
            }
            return $contact;
        }
        return false;
    }
    /**
     * 将客户的主要联系人信息同步到客户表中
     *
     * @param int $client_id    客户id
     * @return bool
     */
    function asyncPrimaryContact($client_id)
    {
        if($contact = $this->getPrimaryContact($client_id))
        {
            $ClientModel = new ClientModel();
            $record = array(
            'contact_name'      => $contact['name'],
            'contact_email'     => $contact['email'],
            'contact_msn'       => $contact['msn'],
            'contact_qq'        => $contact['qq'],
            'contact_cellphone' => $contact['cellphone'],
            );
            return $ClientModel->update($record, 'id=' . $client_id);
        }
        return false;
    }
}